package com.sy.controller;

import com.sy.bean.JwtOperation;
import com.sy.dto.JsonResult;
import com.sy.exception.ParamException;
import com.sy.exception.PermissionException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("testJwt")
public class JwtController {
    @Autowired
    private JwtOperation jwtOperation;


    @RequestMapping(value = "del", method = RequestMethod.DELETE)
    public JsonResult del(@RequestHeader("auth-token") String token, HttpServletResponse res) {
        //这里的校验合法性操作应当在业务层中完成
        JsonResult result = new JsonResult();
        try {
            //头信息中没有token
            if (StringUtils.isBlank(token)) {
                throw new ParamException("请先进行登录");
            }

            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            //根据token无法得到claims
            if (null == claims) {
                throw new ParamException("请先进行登录");
            }

            //判断认证成功的用户中有无执行当前操作需要的权限
            String needPermission = "admin";
            if (!((List<String>) claims.get("roles")).contains(needPermission)) {
                throw new PermissionException("权限不够");
            }

            //删除成功
            result.setCode(204);
        } catch (ParamException | ExpiredJwtException | MalformedJwtException e) {
            e.printStackTrace();
            result.setCode(401);
            if (e instanceof ExpiredJwtException) {
                result.setError("登录信息已过期");
            } else {
                result.setError(e.getMessage());
            }
        } catch (PermissionException e) {
            e.printStackTrace();
            result.setCode(403);
            result.setError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError("服务器异常");
        }
        //这里应该把http状态码设置成和json中code一样
        //res.setStatus(result.getCode());
        return result;

    }


}
